from redis import RedisError
from rest_framework import serializers
from django_redis import get_redis_connection
# Serializer
# ModelSerializer
from users.models import User
import logging

logger = logging.getLogger('meiduo')


class RegisterSMSCodeSerializer(serializers.Serializer):
    text = serializers.CharField(label="图片验证码", max_length=4, min_length=4, required=True)
    image_code_id = serializers.UUIDField(label="验证码唯一性id")

    def validate(self, attrs):
        text = attrs['text']
        image_code_id = attrs['image_code_id']
        rest_conn = get_redis_connection('code')
        redis_text = rest_conn.get('img_%s' % image_code_id)
        if redis_text is None:
            raise serializers.ValidationError('图片验证码已过期')
        try:
            rest_conn.delete('img_%s' % image_code_id)
        except RedisError as e:
            logger.error(e)
        if redis_text.decode().lower() != text.lower():
            raise serializers.ValidationError('图片验证码输入错误')
        return attrs


